package com.whu.controller;

import com.whu.domain.Commodity;
import com.whu.service.CommodityServiceInterface;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/commodities")
public class CommodityController {
    @Resource
    private CommodityServiceInterface commodityServiceInterface;

    @PostMapping
    public Result<Boolean> add(@RequestBody Commodity commodity){
        if(commodityServiceInterface.add(commodity)){
            return new Result<>(Code.CODE_ADD_SUCCESS, true,"添加成功！");
        }else{
            return new Result<>(Code.CODE_ADD_ERROR, false,"添加失败，请重试！");
        }
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Integer id){
        if(commodityServiceInterface.delete(id)){
            return new Result<>(Code.CODE_DELETE_SUCCESS,true,"删除成功!");
        }else{
            return new Result<>(Code.CODE_DELETE_ERROR,false,"删除失败，请重试！");
        }
    }

    @PutMapping
    public Result<Boolean> update(@RequestBody Commodity commodity){
        if(commodityServiceInterface.update(commodity)){
            return new Result<>(Code.CODE_UPDATE_SUCCESS,true,"更新成功");
        }else{
            return new Result<>(Code.CODE_UPDATE_ERROR,false,"更新失败，请重试！");
        }

    }

    @GetMapping("/id/{id}")
    public Result<List<Commodity>> getById(@PathVariable Integer id){
        if(commodityServiceInterface.getById(id).size()>0){
            return new Result<>(Code.CODE_GETBYID_SUCCESS,commodityServiceInterface.getById(id),"查询成功!");
        }else{
            return new Result<>(Code.CODE_GETBYID_ERROR,commodityServiceInterface.getById(id),"查询失败！");
        }

    }

    @GetMapping("/name/{name}")
    public Result<List<Commodity>> getByName(@PathVariable String name){

        if(commodityServiceInterface.getByName(name).size()>0){
            return new Result<>(Code.CODE_GETBYNAME_SUCCESS,commodityServiceInterface.getByName(name),"查询成功!");
        }else{
            return new Result<>(Code.CODE_GETBYNAME_ERROR,commodityServiceInterface.getByName(name),"查询失败！");
        }
    }

    @GetMapping
    public Result<List<Commodity>> getAll(){
        if(commodityServiceInterface.getAll().size()>0){
            return new Result<>(Code.CODE_GETALL_SUCCESS,commodityServiceInterface.getAll(),"查询成功!");
        }else{
            return new Result<>(Code.CODE_GETALL_ERROR,commodityServiceInterface.getAll(),"查询失败！");
        }
    }
}
